package guijavacommander;

import javax.swing.tree.DefaultTreeModel;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.List;
import java.util.ArrayList;
import java.util.Collections;

/**
 * User: Deady
 * Date: 15.07.2009
 * Time: 13:31:54
 */
class FileSystemModel extends DefaultTreeModel {

    public FileSystemModel() {
        super(new FileTreeNode(new File("/")));
    }

    public FileSystemModel(FileTreeNode root) {
        super(root);
    }

    public FileTreeNode findNode(File file) throws FileNotFoundException {
        List<File> parents = new ArrayList<File>();
        parents.add(file);
        File parent = file.getParentFile();
        while (parent!=null) {
            parents.add(parent);
            parent = parent.getParentFile();
        }
        Collections.reverse(parents);

        FileTreeNode node = (FileTreeNode) getRoot();
        parents.remove(0); //remove root
        for (File parent1 : parents) {
            boolean found = false;
            for (FileTreeNode child : node.getChildren()) {
                if (child.getUserObject().equals(parent1)) {
                    node = child;
                    found = true;
                    break;
                }
            }
            if (!found) {
                throw new FileNotFoundException("File not found: " + parent1.getAbsolutePath());
            }
        }
        return node;
    }

}
